package com.lsh.oms.worker.service.task;

import com.lsh.base.http.client.core.HttpClient;
import com.lsh.base.lang.Exceptions;
import com.lsh.base.lang.Maps;
import com.lsh.base.lang.json.Jsons;
import com.lsh.oms.core.enums.TaskStatus;
import com.lsh.oms.core.enums.TaskType;
import com.lsh.oms.core.model.po.OmsTask;
import com.lsh.oms.worker.service.base.OmsSimpleElasticJob;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Optional;

import static com.lsh.base.http.client.ResponseAssertions.assertSuccess;
import static com.lsh.base.lang.bean.Beans.getMap;
import static com.lsh.base.lang.bean.Beans.getString;

@Component
public class HttpTrigger extends OmsSimpleElasticJob {

    private static Logger LOGGER = LoggerFactory.getLogger(HttpTrigger.class);

    @Resource(name = "apache.http.client")
    private HttpClient https;

    @Override
    protected Integer getFetchSize() {
        return 100;
    }

    @Override
    protected TaskType getTaskType() {
        return TaskType.HTTP_TRIGGER;
    }

    @Override
    protected List<Integer> dealTaskStatus() {
        return Arrays.asList(TaskStatus.TASK_UN_DEAL.getCode(), TaskStatus.TASK_DEAL_FAIL.getCode());
    }

    @Override
    protected int process(OmsTask task) {
        Map<String, Object> request = Jsons.fromJsonString(task.getExt());
        LOGGER.info("find http trigger task: {}, specification: {}", task.getRefCode(), request);
        if (request != null && !request.isEmpty()) {
            try {
                Map<String, Object> headers = Maps.newHashMap("venderId", task.venderId.toString());
                Optional.ofNullable(getMap(request, "headers")).ifPresent(headers::putAll);
                Map<String, Object> response = https.exchange(getString(request, "method"), getString(request, "url"), headers, getMap(request, "entity"));
                assertSuccess(response);
                return 1;
            } catch (Exception e) {
                Exceptions.stackTraceLineByLine(e);
            }
        }
        return -1;
    }
}
